package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.config.KeyConfig;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.ShiroMd5Util;
import com.wmh.baseservice.common.utils.SignDecodeUtil;
import com.wmh.baseservice.common.utils.encrypt.RSAUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.Code;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantIncomeExpend;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantIncomeExpendService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantPlotRegionService;
import com.wmh.baseservice.merchant.service.MerchantVegetablePlotService;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wmh generator
 * @since 2021-12-24
 */
@Api(tags = "商家端-商家账号信息相关接口")
@RestController
@RequestMapping(value = "merchant/merchantInfo", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
public class MerchantInfoController {

    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private MerchantIncomeExpendService merchantIncomeExpendService;

    @ApiOperation("商家详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @RequiresPermissions(logical = Logical.OR, value = {"所有权限"})
    public String detail() {
        JSONObject object = new JSONObject(true);
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        //合伙人信息
        List<MerchantInfo> merchantInfos = merchantInfoService.listForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.PARENT_ID, merchantInfo.getUsId())
                .select(MerchantInfo.getFields(MerchantInfo.PASSWORD, MerchantInfo.SALT)));
        merchantInfos.forEach(item -> {
            UsInfo info = usInfoService.getByIdForUpdate(item.getUsId());
            item.setNick(info.getNick());
            item.setAvatar(info.getAvatar());
        });
        object.put("son", merchantInfos);
        return ReturnBody.success(object);
    }

    @ApiOperation("修改密码")
    @PostMapping("updatePwd")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updatePwd(String oldPassword, String newPassword, String verifyCode, String verifySign) throws Exception {
        //验证码验证
        JSONObject verifyResult = SignDecodeUtil.codeMatches(verifyCode, verifySign, 1000000);
        if (!verifyResult.getBoolean("isSuccess")) {
            return ReturnBody.error(Code.IMAGE_CODE_ERROR, verifyResult.getString("errorMessage"));
        }
        oldPassword = RSAUtil.decryptByPrivateKey(oldPassword);
        newPassword = RSAUtil.decryptByPrivateKey(newPassword);
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (!ShiroMd5Util.decodePwd(merchantInfo.getPassword(), oldPassword + KeyConfig.SHIRO_SALE, merchantInfo.getSalt())) {
            return ReturnBody.error("原密码错误");
        }
        merchantInfo.setPassword(ShiroMd5Util.encodePwd(newPassword + KeyConfig.SHIRO_SALE, merchantInfo.getSalt()));
        if (!merchantInfoService.updateById(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("getName")
    @PostMapping("getName")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String getName() {
        JSONObject object = new JSONObject(true);
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        object.put("name",merchantInfo.getName());
        object.put("storeName",merchantInfo.getStoreName());
        object.put("storeAvatar",merchantInfo.getStoreAvatar());
        return ReturnBody.success(object);
    }

    @ApiOperation("流水明细")
    @PostMapping("incomeList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String incomeList(PageInfo pageInfo) {
        Long id = (Long) request.getAttribute("id");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<MerchantIncomeExpend> pageResult = new PageUtil<MerchantIncomeExpend>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantIncomeExpend.MERCHANT_ID, id);
            merchantIncomeExpendService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }


}
